package model

import (
	"chat/common/msg"
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
)

// 服务启动时初始化全局UserDao
var MyUserDao *UserDao

// 完成对User的操作
type UserDao struct {
	pool *redis.Pool
}

// 使用工厂模式创建UserDao
func NewUserDao(pool *redis.Pool) (userDao *UserDao) {
	userDao = &UserDao{
		pool: pool,
	}
	return
}

func (this *UserDao) queryUserById(conn redis.Conn, id int) (user *msg.User, err error) {
	res, err := redis.String(conn.Do("HGet", "users", id))
	if err != nil {
		if err == redis.ErrNil {
			//  redis.ErrNil 没有找到对应id
			err = ERROR_USER_NOTEXISTS
		}
		return
	}
	// 反序列化user
	err = json.Unmarshal([]byte(res), &user)
	if err != nil {
		fmt.Println("queryUserById Unmarshal error = ", err)
		return
	}
	return
}

func (this *UserDao) Login(userId int, pwd string) (user *msg.User, err error) {
	conn := this.pool.Get()
	defer conn.Close()
	user, err = this.queryUserById(conn, userId)
	if err != nil {
		return
	}
	if user.Pwd != pwd {
		err = ERROR_USER_PWD
		return
	}
	return
}

func (this *UserDao) Register(user *msg.User) (err error) {
	conn := this.pool.Get()
	defer conn.Close()
	_, err = this.queryUserById(conn, user.UserId)
	if err == nil {
		err = ERROR_USER_EXISTS
		return
	}
	// 说明没有注册过
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("Register Marshal err = ", err)
		return
	}
	// 入库
	_, err = conn.Do("HSet", "users", user.UserId,
		string(data))
	if err != nil {
		fmt.Println("Register HSet err = ", err)
		return
	}
	return
}
